package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.tools.RegexKit;

/**
 * 加盟农资店界面
 * 
 * 
 * @author Administrator Created at 2015-10-13 下午2:39:29
 * @version 1.0
 */
public class JoinInStoresActivity extends BaseActivity implements OnClickListener {

	private ActivityTitle title;
	private EditText shopName, contactPerson, phone, Address, memo;
	private TextView coords;
	private ImageView businessLicense, userCard;
	/* 头像名称 */
	private Bitmap myBitmap;
	private static final String PHOTO_FILE_NAME = "join_photo.jpg";
	private File tempFile;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private static final int MAP_SELECT_REQ = 4;// 打开地图选择

	private static final String TAG = "JoinInStoresActivity";
	private int image;// 0表示营业执照，1标识身份证
	private ApiParam param;
	File fTemp1 = null;// 营业执照临时文件
	File fTemp2 = null;// 身份证临时文件

	String loc = "";

	Intent mapIntent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		setContentView(R.layout.infox_activity_joinin);
		inintView();

	}

	private void inintView() {
		title = (ActivityTitle) findViewById(R.id.infox_joininTitle);
		title.setTitle("加盟农资店");
		title.setViewVersible(title.rightText, title.titleBack);
		title.rightText.setText("提交");
		param = ApiParam.create();
		tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
		title.setViewGone(title.titleSetting, title.titleOther, title.rightLayout, title.titleRefresh, title.titleMsg);
		shopName = (EditText) findViewById(R.id.joinInStoresName);
		contactPerson = (EditText) findViewById(R.id.joinInStoresContactPerson);
		phone = (EditText) findViewById(R.id.joinInStorescontectPhone);
		coords = (TextView) findViewById(R.id.joinInScoresCoords);
		Address = (EditText) findViewById(R.id.joinInScoresAddress);
		businessLicense = (ImageView) findViewById(R.id.joinInScoresBusinessLicense);
		userCard = (ImageView) findViewById(R.id.joinInScoresUserCard);
		memo = (EditText) findViewById(R.id.joinInScoresMemo);
		businessLicense.setOnClickListener(this);
		userCard.setOnClickListener(this);
		title.rightText.setOnClickListener(this);
		coords.setOnClickListener(this);
		try {
			loc = SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_BD_LOCAITON).getString("loc");
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		mapIntent = new Intent(JoinInStoresActivity.this, MapMarkerActivity.class);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.joinInScoresBusinessLicense:
			image = 0;
			chooseImg();
			break;
		case R.id.joinInScoresUserCard:
			image = 1;
			chooseImg();
			break;
		case R.id.joinInScoresCoords:
			startActivityForResult(mapIntent, MAP_SELECT_REQ);
			break;
		case R.id.infox_activitytitle_rightText:
			commit();
			break;
		}
	}

	/**
	 * 提交数据
	 * 
	 * 
	 * @author lkx Created at 2015-11-3 上午10:53:44
	 */
	private void commit() {
		if (TextUtils.isEmpty(shopName.getText().toString()) || TextUtils.isEmpty(contactPerson.getText().toString())
				|| TextUtils.isEmpty(phone.getText().toString()) || TextUtils.isEmpty(Address.getText().toString())) {
			ToastKit.showShort(JoinInStoresActivity.this, "必填项不能为空");
			return;
		}
		if (TextUtils.isEmpty(memo.getText().toString())) {
			ToastKit.showShort(JoinInStoresActivity.this, "请输入简介信息");
			return;
		}
		if (fTemp1 == null) {
			ToastKit.showShort(JoinInStoresActivity.this, "请选择营业执照");
			return;
		}
		if (fTemp2 == null) {
			ToastKit.showShort(JoinInStoresActivity.this, "请选择身份证照");
			return;
		}
		if (RegexKit.isMobile(phone.getText().toString())) {
			param.addParam("title", shopName.getText().toString());
			param.addParam("manage", contactPerson.getText().toString());
			param.addParam("addr", Address.getText().toString());
			param.addParam("memo", memo.getText().toString());
			param.addParam("phone", phone.getText().toString());
			param.addParam("location", loc);
			Api.post("apply/outlet", param, new ApiCallback(JoinInStoresActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					if (result.getCode() == 100) {
						ToastKit.showShort(mContext, "申请成功，审核通过后将会以短信方式通知");
						finish();
					} else {
						ToastKit.showShort(mContext, TextUtils.isEmpty(result.getMsg()) ? "申请失败，请重试" : result.getMsg());
					}
				}

				@Override
				public void handleFailure(Exception e, String msg) {
					ToastKit.showShort(mContext, TextUtils.isEmpty(msg) ? "申请失败，请重试" : msg);
				}
			}, JoinInStoresActivity.this);
		} else {
			ToastKit.showShort(JoinInStoresActivity.this, "请输入正确的联系手机");
		}

	}

	private void chooseImg() {
		new AlertDialog.Builder(this).setTitle("选择图片获取方式").setNegativeButton("相册", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				// 激活系统图库，选择一张图片
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

			}
		}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {

				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				// 判断存储卡是否可以用，可用进行存储
				if (hasSdcard()) {
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
				}
				startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
			}
		}).show();
	}

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 * 
	 * @author lkx Created at 2015-10-17 上午10:53:34
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径

				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {
				if (tempFile != null) {
					crop(Uri.fromFile(tempFile));
				}

			} else {
				ToastKit.showShort(JoinInStoresActivity.this, "未找到存储卡，无法存储照片！");
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				myBitmap = data.getParcelableExtra("data");
				if (image == 0) {

					this.businessLicense.setImageBitmap(myBitmap);
				}
				if (image == 1) {
					this.userCard.setImageBitmap(myBitmap);
				}
				upload();
				tempFile.delete();

			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}

		} else if (requestCode == MAP_SELECT_REQ && resultCode == RESULT_OK) {
			loc = data.getDoubleExtra("lat", -1) + ":" + data.getDoubleExtra("lon", -1) + ":40";
			coords.setText("已定位");
			Address.setText(data.getStringExtra("addr"));
			mapIntent.putExtra("current", false);
			mapIntent.putExtra("lat", data.getDoubleExtra("lat", -1));
			mapIntent.putExtra("lon", data.getDoubleExtra("lon", -1));
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 图片裁剪
	 * 
	 * @param uri
	 * 
	 * @author lkx Created at 2015-10-17 上午10:58:44
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/**
	 * 图片数据拼接
	 * 
	 * 
	 * @author lkx Created at 2015-10-17 下午2:45:38
	 */
	private void upload() {
		if (myBitmap != null) {
			BufferedOutputStream bos = null;

			try {
				if (image == 0) {// 营业执照照
					System.out.println("营业执照照");
					fTemp1 = File.createTempFile("business", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp1));
				}
				if (image == 1) {// 身份证照
					System.out.println("身份证照");
					fTemp2 = File.createTempFile("user", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp2));
				}

				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (image == 0) {// 正面证件照
				param.addParam("pic1", fTemp1);
			}
			if (image == 1) {// 反面证件照
				param.addParam("pic2", fTemp2);
			}

		}

	}
}
